<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchAfterSalesListAPI } from '@/apis/fetchAfterSalesList'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'
import { handleAfterSalesAPI } from '@/apis/handleAfterSales'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

/* ------------------------------- Tabs START ------------------------------- */
const tabConfiguration = [{ name: '全部' }, { name: '待处理' }, { name: '处理中' }, { name: '已完成' }]
const selectedTabName = ref<'全部' | '待处理' | '处理中' | '已完成'>('全部')
/* -------------------------------- Tabs END -------------------------------- */

/* ------------------------------- 列表数据 START ------------------------------- */
// 项目数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<AfterSalesDetail>>(
  fetchAfterSales,
  { isNoMore: d => d?.list.length === d?.total },
)
// 搜索
const { searchText, isOpenSearch, searching, searchResult, fetchSearchResult } = useSearch<AfterSalesDetail>(search as any)

const finalList = computed(() => {
  if (isOpenSearch.value)
    return searchResult.value
  else
    return dataList.value
})

const skeletonLength = ref(6)

watch(finalList, (newVal) => {
  if (newVal.length > 0)
    skeletonLength.value = newVal.length
})

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description useLoadMore 所必需的服务函数
 *
 * @param d - useLoadMore 中的 `data`
 */
async function fetchAfterSales(d?: LoadMoreData<AfterSalesDetail>): Promise<LoadMoreData<AfterSalesDetail>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1
  // 当前状态
  const afterSalesStatusCode = projectConfigStore.afterSalesStatusCode[selectedTabName.value]
  // 发起请求
  const res = await fetchAfterSalesListAPI({
    page: _page.toString(),
    limit: '10',
    status: afterSalesStatusCode as '1' | '2' | '3',
    keyword: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)
  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

async function search() {
  const projectStatusCode = projectConfigStore.projectStatusCode[selectedTabName.value]
  const res = await fetchAfterSalesListAPI({
    page: '1',
    limit: '100',
    status: projectStatusCode as '1' | '2' | '3',
    keyword: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)
  return res.data!
}

onReady(() => {
  if (userInfoStore.belongTo(['0']))
    uni.setNavigationBarTitle({ title: '售后记录' })
  else
    uni.setNavigationBarTitle({ title: '售后管理' })
})
onShow(() => refresh())
onReachBottom(() => loadMore())
/* -------------------------------- 列表数据 END -------------------------------- */

/* ------------------------------- 事件处理 START ------------------------------- */
const handleSearch = useDebounceFn((keyword: string) => {
  searchText.value = keyword
  fetchSearchResult()
}, 500)

async function handleTabChange(e: any) {
  selectedTabName.value = e.name
  uni.pageScrollTo({ scrollTop: 0, duration: 0 })
  refresh()
}

function handleTapItem(item: AfterSalesDetail) {
  router.push({
    name: 'afterSalesDetail',
    params: {
      after_sales_item: JSON.stringify(item),
    },
  })
}

function handleCallContact(phoneNumber?: string) {
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber,
      success: () => { },
      fail: () => { uni.showToast({ title: '呼叫取消', icon: 'none' }) },
    })
  }
  else {
    uni.showToast({ title: '手机号未知', icon: 'none' })
  }
}

async function handleCopewith(item: AfterSalesDetail) {
  if (item.id) {
    try {
      const res = await handleAfterSalesAPI(item.id.toString(), userInfoStore.userInfo!.token!)
      if (res.data?.code === 1) {
        refresh()
        const newItem: AfterSalesDetail = {
          ...item,
          status: 2,
        }
        router.push({
          name: 'afterSalesDetail',
          params: {
            after_sales_item: JSON.stringify(newItem),
          },
        })
      }
    }
    catch (err) {
      uni.showToast({ title: '处理失败', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '处理失败', icon: 'none' })
  }
}

function handleUploadProof(afterId?: string) {
  if (afterId) {
    router.push({
      name: 'uploadProof',
      params: {
        after_id: afterId,
      },
    })
  }
  else {
    uni.showToast({ title: '项目不存在', icon: 'none' })
  }
}
/* -------------------------------- 事件处理 END -------------------------------- */
</script>

<template>
  <!-- 页面 -->
  <view class="min-h-screen bg-#F8F8F8">
    <!-- 顶部搜索栏与 Tab 选项卡 -->
    <view class="z-10 sticky top-0 left-0 w-750rpx bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入业主姓名/手机号"
          @change="handleSearch" @focus="isOpenSearch = true" @blur="isOpenSearch = false"
        />
      </view>
      <Spacer height="10" />
      <uv-tabs
        :list="tabConfiguration" line-color="#FF6D0A" line-width="48rpx"
        :active-style="{ color: '#000000', fontSize: '32rpx', lineHeight: '32rpx' }"
        :inactive-style="{ color: '#999999', fontSize: '28rpx', lineHeight: '28rpx' }"
        :custom-style="{ margin: '0 10rpx' }"
        @change="handleTabChange"
      />
    </view>

    <!-- 骨架屏 -->
    <view v-if="(loading && !loadingMore) || searching" class="p-30rpx bg-#F8F8F8">
      <!-- 骨架屏 Item -->
      <AfterSalesCardUserSkeleton v-for="i in skeletonLength" v-show="userInfoStore.belongTo(['0'])" :key="i" />
      <AfterSalesCardForemanSkeleton v-for="i in skeletonLength" v-show="userInfoStore.belongTo(['2'])" :key="i" />
    </view>

    <block v-else>
      <!-- 真实列表数据 -->
      <uv-list v-if="finalList.length > 0" :custom-style="{ padding: '30rpx', backgroundColor: '#F8F8F8' }">
        <uv-list-item
          v-for="item in finalList" :key="item.id"
          :custom-style="{ borderRadius: '20rpx', marginBottom: '30rpx' }"
        >
          <!-- 卡片 -->
          <AfterSalesCardUser v-if="userInfoStore.belongTo(['0'])" :item="item" @tap="handleTapItem(item)" />
          <AfterSalesCardForeman
            v-if="userInfoStore.belongTo(['2'])"
            :item="item"
            @tap="handleTapItem(item)"
            @call-contact="handleCallContact(item.contacts_mobile)"
            @copewith="handleCopewith(item)"
            @upload-proof="handleUploadProof(item.id?.toString())"
          />
        </uv-list-item>
        <!-- 加载更多 -->
        <uv-load-more v-if="!isOpenSearch && dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
      </uv-list>
      <!-- 页面缺省页 -->
      <PageDefault v-else />
    </block>
  </view>
</template>

<route lang="yaml">
name: 'afterSalesList'
style:
  navigationBarBackgroundColor: '#FFFFFF'
  onReachBottomDistance: 100
layout: 'custom'
</route>
